#!/usr/bin/python


###############################################################################
## start of run.py
###############################################################################


##point_data_table=[  # 83350 records
##  { 'longitude':0, 'latitude':11437 },
##  { 'longitude':18909, 'latitude':28929 },
##]
##
#point_id_table=[  # 83350 records
#]
##
##square_global_table={ # 1 records
##  'edges.east':35866352,
##  'edges.north':33334655,
##  'edges.west':34219848,
##  'edges.south':29489368,
##  'step_longitude':32284,
##  'step_latitude':32587,
##  'count_longitude':51,
##  'count_latitude':118,
##  'count_squares':1413,
##}
##square_data_table=[ # 1413 records
##  { #'location index':0,
##    'edges.east':34252132,
##    'edges.north':31346827,
##    'edges.west':34219848,
##    'edges.south':31314240,
##    'position':56,
##    'first_point':0, # (00000000)
##    'first_shape':0, },
##  { #'location index':1,
##    'edges.east':34284416,
##    'edges.north':31216479,
##    'edges.west':34252132,
##    'edges.south':31183892,
##    'position':170,
##    'first_point':1, # (00000001)
##    'first_shape':85, },
##]
##line_data_table=[ # 101180 records
##  { 'line_pos_index':0, 'from':0, 'from_as_hex':0x00000000, 'to':26148864, 'to_as_hex':0x018F0000, 'first_shape':0, 'street':0 },
##  { 'line_pos_index':1, 'from':65537, 'from_as_hex':0x00010001, 'to':327681, 'to_as_hex':0x00050001, 'first_shape':0, 'street':0 },
##]
##street_name_table=[ # 12449 records
##    { 'index_in_table':0, 'fedirp':0, 'fename':1567, 'fetype':0, 'fedirs':0 },
##    { 'index_in_table':1, 'fedirp':0, 'fename':0, 'fetype':0, 'fedirs':0 },
##]
##street_type_table=[ # 12449 records
##    5, # <one_street_type index_in_table='0' as_byte='5' as_hex='05' />
##    9, # <one_street_type index_in_table='1' as_byte='9' as_hex='09' />
##    10, # <one_street_type index_in_table='2' as_byte='10' as_hex='0A' />
##]


##point_data_table=[  # 83350 records
##  { 'longitude':0, 'latitude':11437 },
##  { 'longitude':18909, 'latitude':28929 },
##]

#---------- from roadmap_types.h -----------------------------------
#/* The cfcc category codes: */

#/* Category: road. */

ROADMAP_ROAD_FIRST       = 1

ROADMAP_ROAD_FREEWAY     = 1
ROADMAP_ROAD_PRIMARY     = 2
ROADMAP_ROAD_SECONDARY   = 3
ROADMAP_ROAD_RAMP        = 4
ROADMAP_ROAD_MAIN        = 5
ROADMAP_ROAD_EXIT        = 6
ROADMAP_ROAD_STREET      = 7
ROADMAP_ROAD_PEDESTRIAN  = 8
ROADMAP_ROAD_4X4         = 9
ROADMAP_ROAD_TRAIL      = 10
ROADMAP_ROAD_WALKWAY    = 11

ROADMAP_ROAD_LAST       = 11

#/* Category: area. */

ROADMAP_AREA_FIRST      = 12

ROADMAP_AREA_PARC       = 12
ROADMAP_AREA_HOSPITAL   = 13
ROADMAP_AREA_AIRPORT    = 14
ROADMAP_AREA_STATION    = 15
ROADMAP_AREA_MALL       = 16

ROADMAP_AREA_LAST       = 16

#/* Category: water. */

ROADMAP_WATER_FIRST     = 17

ROADMAP_WATER_SHORELINE = 17
ROADMAP_WATER_RIVER     = 18
ROADMAP_WATER_LAKE      = 19
ROADMAP_WATER_SEA       = 20

ROADMAP_WATER_LAST      = 20

ROADMAP_CATEGORY_RANGE  = 20


#---------------------------------------------


import sys
import rdb

#RDB_FILE_NAME = "usc77001.rdm.original.2008-04-24"
#RDB_FILE_NAME = "usc77001.rdm.original.2008-05-22"  # newer
if len(sys.argv) != 2:
    print >> sys.stderr, "Usage:\n\t%s <rdb_file_name>\nOutput:\n\tpoints.shp, polylines.shp, polyline.names.utf8.txt" % sys.argv[0]
    sys.exit(-1)
tables = rdb.rdb_load(sys.argv[1])
rdb.rdb_partial_parse(tables)


SOURCE_TAG_LINE = '<tag k="source" v="www.freemap.co.il" />'


print "<?xml version='1.0' encoding='UTF-8'?>"
print "<osm version='0.5' generator='JOSM'>"
#print "<!--  <bound box='32.240109375,34.68121875,32.415890625,35.03278125' origin='http://www.openstreetmap.org/api/0.5' /> -->"

##
## output data: points
##
point_data_table = tables["point"]["data"]
for i in range(0, len(point_data_table)):
    point = point_data_table[i]
    #      <node id='195239876' timestamp='2007-12-29T10:24:13+00:00' user='Jahudie' visible='true' lat='32.4600068' lon='34.9092081' />
    print "  <node id='%d' timestamp='2007-12-29T10:24:13+00:00' user='xxx' visible='true' lat='%2.6f' lon='%2.6f' />" % \
          (i+1, point['_abs_lat'], point['_abs_lon'])
    # TODO: add - print '    ' + SOURCE_TAG_LINE # give credit to freemap.co.il
    
# xml (atribute) string should not include the characters: &"<>
# this function escapes them using the standard xml escape sequences.
def xml_escape(string):
    string = string.replace('&', "&amp;") # make sure no (&) is in the string
    string = string.replace('"', "&quot;") # make sure no quote (") is in the string
    string = string.replace('<', "&lt;") # make sure no less-then (<) is in the string
    string = string.replace('>', "&gt;") # make sure no greater-then (>) is in the string
    return string


##
## output data: lines
##
line_data_table = tables["line"]["data"]
street_type_table = tables["street"]["type"]
#for i in range(0, 1180-1):
#for i in range(0, 0):
for i in range(0, len(line_data_table)):
    line = line_data_table[i]
    print "  <way id='%d' timestamp='2008-02-06T22:17:12+00:00' user='msayag' visible='true'>" % (i+1)
    print "    <nd ref='%d' />" % (line['_from'] +1)
    print "    <nd ref='%d' />" % (line['_to']   +1)
    if line['street']<>65535:
        print '    <tag k="name" v="%s" />' % xml_escape(line['_name']) # todo: use k="name:he"
        street_type = street_type_table[line['street']]
        if street_type == ROADMAP_ROAD_FREEWAY:
            #print "    <tag k='highway' v='motorway' />"
            print "    <tag k='highway' v='trunk' />"
        elif street_type == ROADMAP_ROAD_PRIMARY:
            print "    <tag k='highway' v='primary' />"
        elif street_type == ROADMAP_ROAD_SECONDARY:
            print "    <tag k='highway' v='secondary' />"
        elif street_type == ROADMAP_ROAD_RAMP:
            print "    <tag k='highway' v='trunk_link' />"  # TODO: or motorway_link,trunk_link,primary_link. RAMP/EXIT distinction lost!
        elif street_type == ROADMAP_ROAD_MAIN:
            print "    <tag k='highway' v='unclassified' />"
        elif street_type == ROADMAP_ROAD_EXIT:
            print "    <tag k='highway' v='trunk_link' />"  # TODO: or motorway_link,trunk_link,primary_link. RAMP/EXIT distinction lost!
        elif street_type == ROADMAP_ROAD_STREET:
            print "    <tag k='highway' v='resedential' />"
        elif street_type == ROADMAP_ROAD_PEDESTRIAN:
            print "    <tag k='highway' v='pedestrian' />"  # TODO: or living_street? PEDESTRIAN/WALKWAY distinction lost!
        elif street_type == ROADMAP_ROAD_4X4:
            print "    <tag k='highway' v='track' />"       # TODO: 4x4/TRAIL distinction lost!
        elif street_type == ROADMAP_ROAD_TRAIL:
            print "    <tag k='highway' v='track' />"       # TODO: 4x4/TRAIL distinction lost!
        elif street_type == ROADMAP_ROAD_WALKWAY:
            print "    <tag k='highway' v='pedestrian' />"  # TODO: or living_street? PEDESTRIAN/WALKWAY distinction lost!
        else:
          print '    <tag k="fixme" v="unknown cfcc type %d for street" />' % street_type
          print '    <tag k="cfcc_type" v="%d" /> <!-- %s -->' % (street_type, street_name_str)
    else:
        print '    <tag k="fixme" v="line has no street information" />'
        print "    <tag k='highway' v='motorway' />"
    print '    ' + SOURCE_TAG_LINE # give credit to freemap.co.il
    #print "    <tag k='ref' v='4' />"
    print "  </way>"

polygon_head_table = tables["polygon"]["head"]
polygon_point_table = tables["polygon"]["point"]
string_table = tables["string"]
for i in range(0, len(polygon_head_table)):
    #polygon_head_table=[ # 992 records
    #{ 'first':0, 'count':13, 'name':52, 'cfcc':16, 'filler':0 }, #'line_pos_index':0
    poly = polygon_head_table[i]
    if poly['count'] <= 0:
        continue
    print "  <way id='%d' timestamp='2008-02-06T22:17:12+00:00' user='msayag' visible='true'>" % (i+1+2*len(line_data_table))
    print "    <nd ref='%d' />" % (rdb.point_id_to_index( polygon_point_table[poly['first']], tables)+1)
    for j in range(0, poly['count']-1):
        print "    <nd ref='%d' />" % (rdb.point_id_to_index( polygon_point_table[ j+poly['first'] ], tables)+1)
    # first and last point is the same
    print "    <nd ref='%d' />" % (rdb.point_id_to_index( polygon_point_table[poly['first']], tables)+1)
    #print "    <tag k='highway' v='primary' />"
    name = string_table['landmark'][ poly['name'] ]
    print '    <tag k="name" v="%s" />' % xml_escape(name)
    if poly['cfcc']==16:
      print '    <tag k="place" v="city" />'
    elif poly['cfcc']==20:
      print '    <tag k="natural" v="water" />'
    else:
      print '    <tag k="cfcc_type" v="%d" />' % poly['cfcc']
      print '    <tag k="fixme" v="unknown cfcc type %d for poly" />' % poly['cfcc']
    print '    ' + SOURCE_TAG_LINE # give credit to freemap.co.il
    print "  </way>"



print "</osm>"

